package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.base.MyBaseAdapter;
import com.hd.crdao.bean.ImagePathBean;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.ImageUtil;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GlideImageUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 *
 *@author Programming
 *@date 2017/8/3 0003
 */

public class UpLoadPhotoActivity extends BaseSecondActivity {
    private static final int REQUEST_IMAGE = 100;
    private static final int GET_PHOTO_FROM_CAMERA = 120;
    private static final int PHOTO_EDIT = 102;
    private static final int PHOTO_EDIT_SUCCESS = 103;


    public ArrayList<String> imagePaths = new ArrayList<>();

    public DisPlaysImageAdapter disPlaysImageAdapter;
    @BindView(R.id.uploadphoto_head)
    ExpandHeadView mUploadphotoHead;
    @BindView(R.id.gridview_pic)
    GridView mGridviewPic;
    @BindView(R.id.maxsizeDetail)
    TextView mMaxSizeDetail;
    private int recordPosition;

    @Override
    protected int setContentView() {
        return R.layout.activity_uploadphoto;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        ALog.d("左边被点击");
        return mUploadphotoHead;
    }

    @Override
    protected void initView() {
        initData();
        initEvent();
    }

    /**
     * 在第一次加载的时候,
     */
    private void initData() {
        boolean isNotMain = getIntent().getBooleanExtra("isFromMain", true);
        imagePaths = getIntent().getStringArrayListExtra("imagePaths");
        ALog.d("赋值之后" + imagePaths.size() + "");
        if (isNotMain) { //如果是从主页点击过来
            if (imagePaths.size() < 12) {       //把集合补成长度为12
                int lastHasDataOfPosition = getLastHasDataOfPosition() + 1;
                for (int i = lastHasDataOfPosition; i < 12; i++) {
                    imagePaths.add("");
                }
            }
        }
        ALog.d("赋值之后" + imagePaths.size() + "");
        disPlaysImageAdapter = new DisPlaysImageAdapter(imagePaths);
        mGridviewPic.setAdapter(disPlaysImageAdapter);

        updateImageSum();
    }


    /**
     * 更新当前张数
     */
    private void updateImageSum() {
        int num = getEmptyNum();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("最多可拍12张图片,您已拍" + num + "张");
        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
        spannableStringBuilder.setSpan(redSpan, 13, spannableStringBuilder.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mMaxSizeDetail.setText(spannableStringBuilder);
    }

    /**
     * 获取当前有多少张不为空的照片
     *
     * @return
     */
    private int getEmptyNum() {
        int num = 0;
        for (int i = 0; i < imagePaths.size(); i++) {
            if (!TextUtils.isEmpty(imagePaths.get(i))) {
                num++;
            }
        }
        return num;
    }

    private void initEvent() {
        mGridviewPic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (TextUtils.isEmpty(imagePaths.get(position))) {
                    showCameraPopwidow(true, imagePaths.get(position), position);
                } else {
                    showCameraPopwidow(false, imagePaths.get(position), position);
                }
            }
        });
    }


    /**
     * //弹出有拍照图库的popupwindow 和它的点击事件处理
     *
     * @param isEmpty   是否有图片,如果有图片表示弹出编辑删除取消选项
     * @param imagePath
     * @param position
     */
    private void showCameraPopwidow(final boolean isEmpty, final String imagePath, final int position) {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.camera_pop_menu, null);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        Button btnCamera = (Button) popView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) popView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) popView.findViewById(R.id.btn_camera_pop_cancel);
        if (isEmpty) {
            btnCamera.setText("拍照");
            btnAlbum.setText("相册");
            btnCancel.setText("取消");
        } else {
            btnCamera.setText("编辑");
            btnAlbum.setText("删除");
            btnCancel.setText("取消");
        }
        final PopupWindow popWindow = getPopupWindow(parent, popView, width, height);


        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_camera_pop_camera:
                        if (isEmpty) {
                            recordPosition = position;
                            pickPicFromCam(imagePaths, recordPosition);
                        } else {
                            recordPosition = position;
                            Intent intent = new Intent(UIUtils.getContext(), EditPictureActivity.class);
                            intent.putExtra("singleImagePath", new String[]{String.valueOf(recordPosition), imagePath});
                            startActivityForResult(intent, PHOTO_EDIT);
                        }
                        break;
                    case R.id.btn_camera_pop_album:
                        if (isEmpty) {
                            recordPosition = position;
                            pickPicFroGallery();
                        } else {
                            recordPosition = position;
                            deleteImage(recordPosition);
                        }
                        break;
                    case R.id.btn_camera_pop_cancel:
                        break;
                    default:
                        break;
                }
                popWindow.dismiss();
            }


        };

        btnCamera.setOnClickListener(listener);
        btnAlbum.setOnClickListener(listener);
        btnCancel.setOnClickListener(listener);


    }

    /**
     * 删除图片
     *
     * @param
     * @param recordPosition
     */
    private void deleteImage(int recordPosition) {
        imagePaths.set(recordPosition, "");
        updateUI();
    }

    /**
     * 从相册里面取图片
     */
    private void pickPicFroGallery() {
        Intent intent = new Intent(UIUtils.getContext(), MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 12 - getEmptyNum());
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        ArrayList<String> list = new ArrayList<>();
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, list);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    /**
     * 从相机中获取图片
     *
     * @param imagePaths
     * @param position
     */
    private void pickPicFromCam(ArrayList<String> imagePaths, int position) {
        Intent intent = new Intent(UIUtils.getContext(), TakeCameraActivity.class);
        intent.putStringArrayListExtra("imagePaths", imagePaths);       //如果能够进入拍照界面,集合的长度一定为12
        intent.putExtra("curPosition", position);       //点击的是哪一张默认图片
        startActivityForResult(intent, GET_PHOTO_FROM_CAMERA);
    }


    public void updateUI() {
        updateImageSum();
        disPlaysImageAdapter = new DisPlaysImageAdapter(imagePaths);
        mGridviewPic.setAdapter(disPlaysImageAdapter);
        disPlaysImageAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {      //从相册获取图片
            ArrayList<String> tempList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            //里面有一些照片
            ChangeImageLoader(tempList);
            resetData(recordPosition, tempList);
            updateUI();

        } else if (resultCode == GET_PHOTO_FROM_CAMERA) {   //十二连拍的功能
            ArrayList<String> list = data.getStringArrayListExtra("imagePaths");
            ALog.d(list.toString());
       //     ChangeImageLoader(list);
            resetData(recordPosition, list);
            updateUI();

        } else if (requestCode == PHOTO_EDIT && resultCode == PHOTO_EDIT_SUCCESS) {
            String[] newpaths = data.getStringArrayExtra("imagePath");
            imagePaths.set(recordPosition, newpaths[1]);
            ALog.d("从编辑图片获取的图片路径:" + newpaths[1]);
            updateUI();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @NonNull
    private PopupWindow getPopupWindow(View parent, View popView, int width, int height) {
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        return popWindow;
    }


    private class DisPlaysImageAdapter extends MyBaseAdapter<String> {
        private DisPlaysImageAdapter(List<String> dataSets) {
            super(dataSets);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(UIUtils.getContext(), R.layout.itme_showpic, null);
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image_item);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            GlideImageUtils.loadImage(mDataSets.get(position),R.drawable.photo_on_2x,viewHolder.imageView);
            int lastHasDataOfPosition = getLastHasDataOfPosition();
            if (position == 0) {
                viewHolder.imageView.setVisibility(View.VISIBLE);
            }
            if (lastHasDataOfPosition < 12) {
                if (position > lastHasDataOfPosition) {
                    viewHolder.imageView.setVisibility(View.GONE);
                    if (position == lastHasDataOfPosition + 1 && lastHasDataOfPosition != 0) {
                        viewHolder.imageView.setVisibility(View.VISIBLE);
                    } else if (position == 1 && 12 - reCountIsEmpty().size() == 1) {
                        viewHolder.imageView.setVisibility(View.VISIBLE);
                    }
                } else {
                    ALog.d("显示的位置是" + position);
                    viewHolder.imageView.setVisibility(View.VISIBLE);
                }
            } else {
                viewHolder.imageView.setVisibility(View.VISIBLE);


            }


            return convertView;
        }

        private class ViewHolder {
            ImageView imageView;
        }

    }

    /**
     * 提供给release页面使用的  设置数据时再进行替换
     */
    @Override
    public void onBackPressed() {
        ImagePathBean imagePathBean = new ImagePathBean();
        imagePathBean.setList(imagePaths);
        EventBus.getDefault().post(imagePathBean);
        finish();
    }


    public void resetData(int firstPosition, ArrayList<String> tempList) {
        int count = 0;
        ArrayList<Integer> list = reCountIsEmpty();
        ALog.d("索引的集合是" + list.toString());
        String firstSelect = tempList.get(0);

        imagePaths.set(firstPosition, firstSelect);
        tempList.remove(0);
        ALog.d("" + imagePaths.indexOf(firstSelect));
        list = reCountIsEmpty();
        ALog.d("索引的集合是" + list.toString());
        if (!tempList.isEmpty()) {
            for (int i = 0; i < tempList.size(); i++, count++) {
                imagePaths.set(list.get(count), tempList.get(i));
                ALog.d("索引是" + list.get(count) + ",值是" + tempList.get(i));
            }
        }
    }

    /**
     * 重新统计集合中哪些是空的数据的索引集合
     *
     * @return
     */
    private ArrayList<Integer> reCountIsEmpty() {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < imagePaths.size(); i++) {
            if (TextUtils.isEmpty(imagePaths.get(i))) {
                list.add(i);
            }
        }
        return list;
    }

    /**
     * 获取最后一个有值的索引是什么
     *
     * @return 返回最后一个不为空值的索引是什么
     */
    private int getLastHasDataOfPosition() {
        int recordpos = 0;
        if (!imagePaths.isEmpty()) {
            for (int i = 0; i < imagePaths.size(); i++) {
                if (!TextUtils.isEmpty(imagePaths.get(i))) {
                    recordpos = i;
                }
            }
            return recordpos;
        } else {
            return recordpos;
        }
    }


    private void ChangeImageLoader(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            if (!TextUtils.isEmpty(list.get(i))) {
                try {
                    Bitmap bitmap = BitmapFactory.decodeFile(list.get(i));
                    File file = new File(list.get(i));
                    ImageUtil.saveMyBitmap(file,bitmap);
                    ALog.d("当前是第" + i + "张图片的大小为:" + Formatter.formatFileSize(UIUtils.getContext(), file.length()));
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

    }
}
